package cn.com.web.Servlet;

import cn.com.domain.Customer;
import cn.com.domain.Room;
import cn.com.domain.User;
import cn.com.service.CustomerService;
import cn.com.service.RoomService;
import cn.com.service.UserService;
import cn.com.service.impl.CustomerServiceImpl;
import cn.com.service.impl.RoomServiceImpl;
import cn.com.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService=new UserServiceImpl();
        User user = userService.findUserBynameAndPassword(username, password);
        //如果找到了
        if (user!=null){
            //user弄进session域里并且添加Cookie以便下次不用再登录了
            session.setAttribute("user",user);

            Cookie cookie=new Cookie("autologin",username+"-"+password);
            response.addCookie(cookie);
            CustomerService service=new CustomerServiceImpl();
            List<Customer> customers = service.findAll();
            session.setAttribute("customers",customers);
            RoomService roomService=new RoomServiceImpl();
            List<Room> rooms = roomService.findAll();
            session.setAttribute("rooms",rooms);
            response.sendRedirect(request.getContextPath()+"/FindCustomerByPageServlet?currentPage=1&rows=5");
        }else
        {
            //更改msg并重定向到login.jsp
            session.setAttribute("msg","用户名或者密码错误！");
            response.sendRedirect(request.getContextPath()+"/login.jsp");

        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
